package com.scriptlib;

import android.app.Instrumentation;
import android.os.SystemClock;
import android.view.MotionEvent;

public class Automation {//在沙箱环境下无需无障碍和root权限的模拟点击

private final Instrumentation instrumentation;

    public Automation() {
        instrumentation = new Instrumentation();
    }

    public void Tap(int x, int y) {
        long time = SystemClock.uptimeMillis();

        instrumentation.sendPointerSync(MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, x, y, 0));
        instrumentation.sendPointerSync(MotionEvent.obtain(time + 20, time + 20, MotionEvent.ACTION_UP, x, y, 0));
    }

    public void Swipe(int sx, int sy, int ex, int ey, int timeout) {
        long time = SystemClock.uptimeMillis();
        instrumentation.sendPointerSync(MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, sx, sy, 0));
        int step = 0;
        int step_1 = Math.abs(ex - sx) / 20;
        int step_2 = Math.abs(ey - sy) / 20;
        if (step_1 >= step_2)
            step = step_1;
        else
            step = step_2;
        int _timeout = timeout / step;

        for (int i = 1; i < step; i++) {
            long _time = time + i * _timeout;
            instrumentation.sendPointerSync(MotionEvent.obtain(_time, _time, MotionEvent.ACTION_MOVE, sx + ((ex - sx) / step * i), sy + ((ey - sy) / step * i), 0));
        }
        long _time = time + step * _timeout;
        instrumentation.sendPointerSync(MotionEvent.obtain(_time, _time, MotionEvent.ACTION_MOVE, ex, ey, 0));
        instrumentation.sendPointerSync(MotionEvent.obtain(_time + _timeout, _time + _timeout, MotionEvent.ACTION_UP, ex, ey, 0));
    }
}
